<template>
  <h1>测试vee-validate</h1>
  <!--
    ref: 引用；后边手动兜底校验要使用
    validation-schema： 用来指定校验规则(这里的规则)
    v-slot: 作用域插槽，如果校验失败，errors中会保存校验失败的结果
  -->
  <Form  ref="target" :validation-schema="schema" v-slot="{ errors }">
    <Field v-model="formData.mobile" name="mobile" type="text" placeholder="请输入手机号" />
    <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    <Field v-model="formData.password" name="password" type="password" placeholder="请输入密码" />
    <button @click="submit">登录</button>
  </Form>
</template>
<script>
import { Form, Field } from 'vee-validate'
import { ref, reactive } from 'vue'
export default {
  components: { Form, Field },
  setup () {
    const target = ref(null)
    const formData = reactive({ mobile: '13612345678', password: '123456' })

    // 定义校验规则
    // return 字符串，表示校验不通过; return true 表示校验通过
    const schema = {
      mobile (value) {
        if (!value) return '请输入手机号'
        if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式错误'
        return true
      },
      password (value) {
        if (!value) return '请输入密码'
        if (!/\d{6}$/.test(value)) return '密码格式错误'
        return true
      }
    }
    const submit = () => {
      // 手动兜底校验，表单数据是否正确
      target.value.validate().then(res => {
        console.log(res)
      })
    }
    return { formData, schema, submit, target }
  }
}
</script>
